package A099queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class B003_LinkedBlockingQueue_put_take_之阻塞和超时控制 {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<>(3);

        new Thread(() -> {
            try {
                blockingQueue.put("a");
                System.out.println("插入元素\ta");
                blockingQueue.put("b");
                System.out.println("插入元素\tb");
                blockingQueue.put("c");
                System.out.println("插入元素\tc");
                blockingQueue.put("d");//将会阻塞,直到主线程take()
                System.out.println("插入元素\td");
                System.out.println("it was blocked.");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        TimeUnit.SECONDS.sleep(2);

        try {

            System.out.println("取出元素\t" + blockingQueue.take());
            System.out.println("取出元素\t" + blockingQueue.take());
            System.out.println("取出元素\t" + blockingQueue.take());
            System.out.println("取出元素\t" + blockingQueue.take());

            System.out.println("Blocking...");
            blockingQueue.take();//将会阻塞

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
